package com.zxl.live.screen.screen.ui.widget.anim;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by Administrator on 2018/1/23.
 */

public class ZipDataHelper {

    private ZipFile zipFile;

    private List<ZipEntry> mList;

    public ZipDataHelper(String path) {
        try {
            mList = new ArrayList<>();
            zipFile = new ZipFile(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void init() {
        mList.clear();
        Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile.entries();
        while (enumeration.hasMoreElements()) {
            mList.add(enumeration.nextElement());
        }
        Collections.sort(mList, new Comparator<ZipEntry>() {
            @Override
            public int compare(ZipEntry o1, ZipEntry o2) {
                return getNumber(o1.getName()) -  getNumber(o2.getName());
            }
        });
    }

    private static int getNumber(String str) {
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return Integer.parseInt(m.replaceAll("").trim());
    }

    public List<ZipEntry> getList() {
        return mList;
    }

    public int size() {
        return mList.size();
    }

    public Bitmap createBitmap(int index) {
        try {
            return BitmapFactory.decodeStream(zipFile.getInputStream(mList.get(index)));
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}
